package edu.ccut.titan.component.impl.directory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import edu.ccut.titan.component.IDirectoryInfo;
import edu.ccut.titan.component.TitanComponentException;

public class TitanDirectoryFactory {
	
	private static final String DIRECTORY_TYPE_FILE_NAME = "directory_type.properties";
																			
	private static TitanDirectoryFactory instance;
	
	static {
		instance = new TitanDirectoryFactory();
	}
	
	private Map<String, Class<?>> directoryClassMap;
	
	private TitanDirectoryFactory() {
		loadDirectoryClass();
	}
	
	public static TitanDirectoryFactory getInstance() {
		return instance;
	}
	
	public IDirectoryInfo createDirectory(String version, String description, String type, String time) throws TitanComponentException {
		try {
			if (this.directoryClassMap.containsKey(type)) {
				Class<?> directoryClass = this.directoryClassMap.get(type);
				
				IDirectoryInfo directoryInfo =  (IDirectoryInfo)directoryClass.newInstance();
				
				directoryInfo.setVersion(version);
				directoryInfo.setDescription(description);
				directoryInfo.setTime(time);
				
				return directoryInfo;
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		
		throw new TitanComponentException("the directory type : " + type + "is not valid");
	}
	
	@SuppressWarnings("unchecked")
	private void loadDirectoryClass() {
		Properties properties = new Properties();
		
		InputStream in = null;
		try {
			in = TitanDirectoryFactory.class.getResourceAsStream(DIRECTORY_TYPE_FILE_NAME);
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		this.directoryClassMap = new HashMap<String, Class<?>>();
		
		for (Enumeration propertyNames = properties.propertyNames(); propertyNames.hasMoreElements();) {
			String key = (String)propertyNames.nextElement();
			String className = properties.getProperty(key);
			
			try {
				this.directoryClassMap.put(key, Class.forName(className));
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
}
